import { Injectable } from '@nestjs/common'
import { CreateUserDto } from './dto/create-user.dto'
import { UpdateUserDto } from './dto/update-user.dto'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, Like } from 'typeorm'
import { User } from './entities/user.entity'
import { Post } from 'src/post/entities/post.entity'
import { PostService } from './../post/post.service'
@Injectable()
export class UserService {
  constructor(
    // private readonly postService: PostService,
    @InjectRepository(User) private readonly user: Repository<User>,
    @InjectRepository(Post) private readonly post: Repository<Post>
  ) {}

  async addPost(params: {
    title: string
    userId: string
    content: string
    discuss?: string
    topic?:string,
    imgArray?: string[]
    address?: string
  }) {
    console.log(params)
    const userInfo = await this.user.findOne({
      relations: ['posts'],
      where: { id: params.userId },
    })

    if (userInfo) {
      const postList: Post[] = userInfo.posts
      let T = new Post()
      T.title = params.title
      T.content = params.content
      T.imgArray = params.imgArray
      T.discuss = params.discuss
      T.address = params.address
      T.topic = params.topic
      postList.push(await this.post.save(T))
      userInfo.posts = postList
      // console.log(userInfo)
      return this.user.save(userInfo)
    } else {
      console.log('用户不存在')

      return
    }
  }

  async addFollows(query) {
    const fansUserInfo = await this.user.findOne({
      where: {
        id: query.userId,
      },
    })
    const followedUserInfo = await this.user.findOne({
      where: {
        id: query.followsId,
      },
    })

    console.log(fansUserInfo.follows)
    //粉丝的关注列表添加东西
    if (fansUserInfo.follows == null) {
      let followsList = []
      followsList.push(query.followsId)
      fansUserInfo.follows = followsList
    } else {
      let followsList = [...fansUserInfo.follows]
      console.log(followsList)
      followsList.push(query.followsId)
      fansUserInfo.follows = [...new Set(followsList)]
    }

    //被关注者的粉丝列表添加东西
    if (followedUserInfo.fans == null) {
      let fansList = []
      fansList.push(query.userId)
      followedUserInfo.fans = fansList
    } else {
      let fansList = [...followedUserInfo.fans]
      console.log(fansList)
      fansList.push(query.userId)
      followedUserInfo.fans = [...new Set(fansList)]
    }
    this.user.save(fansUserInfo)
    return this.user.save(followedUserInfo)
  }
  //添加粉丝的方法
  async addFans(query) {
    const userInfo = await this.user.findOne({
      where: {
        id: query.userId,
      },
    })
    let fansList = [...userInfo.fans]
    console.log(fansList)
    fansList.push(query.fansId)
    userInfo.follows = fansList
    return this.user.save(userInfo)
  }

  async findPostByPage(query) {
    const res = await this.user.find({
      relations: ['posts', 'commits'],
      where: {
        id: query.userId,
      },
    })
    let posts = res[0].posts.sort((a, b) => {
      return (
        new Date(b.create_time).getTime() - new Date(a.create_time).getTime()
      )
    })
    console.log(posts)
    const total = posts.length
    const data = []
    for (
      let i = (query.page - 1) * query.pageSize;
      i < query.page * query.pageSize;
      i++
    ) {
      data.push(posts[i])
    }

    return { data, total }
  }

  async create(createCrudDto: CreateUserDto) {
    const r: any = await this.user.find({
      where: { mobile: createCrudDto.mobile },
    })
    console.log(r)

    if (r[0]) {
      console.log('存在')

      return
    } else {
      console.log('新建')
      const data = new User()
      data.mobile = createCrudDto.mobile
      data.password = createCrudDto.password
      console.log(data)
      return this.user.save(data)
    }
  }

  findLike(query: { keyword: string }) {
    return this.user.find({
      relations: ['posts'],
      where: {
        nickname: Like(`%${query.keyword}%`),
      },
    })
  }
  findAll() {
    return this.user.find({
      relations: ['posts'],
    })
  }
  login(query: {mobile:string,password:string}) {
    if (this.checkPhone(query.mobile)) {
      return this.user.find({
        where: {
          mobile: query.mobile,
          password:query.password
        },
      })
     }
  }

  findOne(id: string) {
    if (this.checkPhone(id)) {
      console.log('to mobile')

      return this.user.find({
        where: {
          mobile: id,
        },
      })
    } else {
      console.log('toid')

      return this.user.find({
        relations: ['posts'],
        where: {
          id: id,
        },
      })
    }
  }

  update(id: string, updateUserDto: UpdateUserDto) {
    console.log('更新')

    return this.user.update(id, updateUserDto)
  }

  remove(id: number) {
    return this.user.delete(id)
  }

  checkPhone = (m) => {
    var mobile = m
    var tel = /^0\d{2,3}-?\d{7,8}$/
    var phone = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/
    if (mobile.length == 11) {
      //手机号码
      if (phone.test(mobile)) {
        console.log(mobile)
        return true
      }
    } else if (mobile.length == 13 && mobile.indexOf('-') != -1) {
      //电话号码
      if (tel.test(mobile)) {
        console.log(mobile)
        return true
      }
    }
    return false
  }
}
